using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBarPool : MonoBehaviour
{
    public GameObject healthBarPrefab;
    public int poolSize = 10;
    public float displayTime = 4f;

    private List<GameObject> healthBarsPool;

    private void Start()
    {
        // 初始化血量条池
        InitializePool();
    }

    private void InitializePool()
    {
        healthBarsPool = new List<GameObject>();
        // 创建并初始化血量条对象，并将其放入池中
        for (int i = 0; i < poolSize; i++)
        {
            GameObject healthBar = GameObject.Instantiate( healthBarPrefab);
            healthBar.transform.SetParent(this.transform);
            healthBar.SetActive(false);
            healthBarsPool.Add(healthBar);
        }
    }

    public void ShowHealthBar(Transform transform, float healthPercentage)
    {
        GameObject healthBar = CheckHasShowed(transform);
        if(healthBar==null) healthBar = GetInactiveHealthBar();
    
        healthBar.GetComponent<HealthSliderController>().SetFollowAndValue(transform, healthPercentage);
        healthBar.SetActive(true);

        StartCoroutine(HideHealthBar(healthBar, displayTime, healthBar.GetComponent<HealthSliderController>().activedTime));
    }

    private GameObject GetInactiveHealthBar()
    {
        // 在池中查找未激活的血量条
        foreach (var healthBar in healthBarsPool)
        {
            if (!healthBar.activeInHierarchy)
            {
                return healthBar;
            }
        }

        // 如果没有未激活的血量条，创建一个新的血量条并将其添加到池中
        GameObject newHealthBar = Instantiate(healthBarPrefab);
        newHealthBar.SetActive(false);
        healthBarsPool.Add(newHealthBar);

        return newHealthBar;
    }

    private GameObject CheckHasShowed(Transform transform){
        foreach(var healthBar in healthBarsPool){
            if(healthBar.activeSelf && healthBar.GetComponent<HealthSliderController>().targetTransform == transform){
                return healthBar;
            }
        }return null;
    }



    private IEnumerator HideHealthBar(GameObject targetObject, float delayTime, int activedTime)
    {
        // 等待指定的时间
        yield return new WaitForSeconds(delayTime);

        if(activedTime == targetObject.GetComponent<HealthSliderController>().activedTime)
            targetObject.SetActive(false);
    }
}
